package com.lzq.badminton.controller;

import com.lzq.badminton.service.UserService;
import com.lzq.community.domain.vo.Pager;
import com.lzq.community.domain.vo.ResponseResult;
import com.lzq.community.util.CommunityConstant;
import com.lzq.community.domain.entity.DiscussPost;
import com.lzq.community.domain.entity.Page;
import com.lzq.community.service.impl.ElasticsearchService;
import com.lzq.community.service.impl.LikeService;
import com.lzq.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/search")
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    // search?keyword=xxx
    @GetMapping(path = "/search")
    public ResponseResult search(@PathParam("keyword") String keyword, int pageNum, int pageSize) {
        Pager<Map<String, Object>> page = new Pager<>();
        // 搜索帖子
        org.springframework.data.domain.Page<DiscussPost> searchResult =
                elasticsearchService.searchDiscussPost(keyword, pageNum, pageSize);
        // 聚合数据
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (searchResult != null) {
            for (DiscussPost post : searchResult) {
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 作者
                map.put("user", userService.getById(post.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussPosts.add(map);
            }
        }
        page.setTotal(searchResult == null ? 0 : (int) searchResult.getTotalElements());
        page.setPage(pageNum);
        page.setSize(pageSize);
        page.setData(discussPosts);

        return ResponseResult.okResult(page);
    }

}
